package com.ubs.training.server.dao.impl.jdbc;

import com.ubs.training.server.dao.LinkClientDao;
import com.ubs.training.server.dao.model.Client;
import com.ubs.training.server.dao.model.LinkClient;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.namedparam.BeanPropertySqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcOperations;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;

import javax.sql.DataSource;
import java.util.Collections;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: xubuntu
 * Date: 8/21/12
 * Time: 4:28 AM
 * To change this template use File | Settings | File Templates.
 */
public class NamedParamLinkClientDaoImpl implements LinkClientDao {
    private DataSource ds;

    public NamedParameterJdbcOperations ops;

    public void setOps(NamedParameterJdbcOperations ops) {
        this.ops = ops;
    }

    public DataSource getDs() {
        return ds;

    }

    public void setDs(DataSource ds) {
        this.ds = ds;
        ops = new NamedParameterJdbcTemplate(ds);
    }

    @Override
    public List<LinkClient> getAll() {
        return ops.query("select id, target_client_id, link_type_id, status, contact_person_name from linked_clients", Collections.EMPTY_MAP, new BeanPropertyRowMapper(LinkClient.class));
    }

    @Override
    public LinkClient getById(int id) {
        return ops.queryForObject("select * from linked_clients " +
                "WHERE id =:linkedId", Collections.singletonMap("linkedId", id),
                new BeanPropertyRowMapper<LinkClient>(LinkClient.class)
        );


    }

    @Override
    public Client getTargetClient(int id) {
        return ops.queryForObject("select fname, lname from client, linked_clients where client.id = :clientId", Collections.singletonMap("clientId", id), new BeanPropertyRowMapper<Client>(Client.class));
    }

    @Override
    public void add(LinkClient linkClient) {
        int id = ops.queryForInt("select next value for cmstr_seq from dual", Collections.EMPTY_MAP);
        linkClient.setId(id);
        ops.update("insert into linked_clients values (:id, :target_client_id, :link_type_id, :status, :contact_person_name)", new BeanPropertySqlParameterSource(linkClient));
    }

    @Override
    public void update(LinkClient linkClient) {
        ops.update("update linked_clients set target_client_id=:target_client_id," +
                " link_type_id=:link_type_id, status=:status," +
                " contact_person_name=:contact_person_name" +
                " where id=:id",
                new BeanPropertySqlParameterSource(linkClient));

    }


    @Override
    public void remove(int id) {
        ops.update("delete from linked_clients where id =:id",Collections.singletonMap("id", id));
    }


}
